package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosLinkmanDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class KitePosLinkmanHandler extends KitePosSceneHandler {

	@Override
	public void handle(KitePosHandlerContext context) {
		IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String serviceOfferId = (String) Optional
            .ofNullable(querySceneInstService.getSceneInst(context.getSceneInstId()))
            .map(KiteSceneInst::getServiceOfferId).orElse("");
        //收入归集集团成员加入、Linkman
        if(KiteStringUtils.equalsAny(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL)){
            context.getPosDto().setLinkman(null);
            return;
        }
        String cateId = CuccPosServiceUtils.getCateId(context.getSceneInstId(), context.getCustId());
		KitePosLinkmanDTO oldLinkman = querySceneInstService
        .getExtParameterValue(context.getSceneInstId(), "linkman");
		List<KiteAttr> publicAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_PUBLIC);
        KiteAttr contactAttrObj = publicAttrs.stream().filter(attr -> KiteStringUtils.equals(attr.getFieldName(), "contactInfo")).findFirst().orElse(null);
        if(Objects.isNull(contactAttrObj)) {
            KitePosLinkmanDTO linkman = context.getPosDto().getLinkman();
            if (Objects.nonNull(linkman) && KiteStringUtils.isEmpty(linkman.getChangeType()) && CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                //非新购场景且没有changeType才赋值为9
                linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
            }
            return ;
        }
        else {
            List<KiteAttr> developerAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_CONTACT);
            if (KiteListUtils.isEmpty(developerAttrs)) {
                if (LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW.equals(serviceOfferId)) {
                    KitePosLinkmanDTO linkman = context.getPosDto().getLinkman();
                    if (Objects.nonNull(linkman) && KiteStringUtils.isEmpty(linkman.getChangeType()) && CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                        linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
                    }
                    return;
                }
                else {
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("未配置【客户联系人】属性");
                }
            }
            KitePosLinkmanDTO linkman = new KitePosLinkmanDTO();
            linkman.setName(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_NAME, "未配置【客户联系人名称】属性"));
            linkman.setPhone(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_TEL, "未配置【客户联系人电话】属性"));
            linkman.setEmail(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_EMAIL, "未配置【客户联系人邮箱】属性"));
            linkman.setAddress(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_ADDRESS, "未配置【客户联系人地址】属性"));
            linkman.setFax(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_FAXNUM, "未配置【客户联系人传真号码】属性"));
            linkman.setFixedPhone(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_FIXEDPHONE, "未配置【客户联系人固话号码】属性"));
            linkman.setPostcode(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_POSTCODE, "未配置【客户联系人邮编】属性"));
            linkman.setPersonIdType(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_CARDTYPE, "未配置【客户联系人证件类型】属性"));
            linkman.setRemark(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_COMMENTS, "未配置【客户联系人备注】属性"));
            //传了空字符串会校验
            if (KiteStringUtils.isEmpty(linkman.getPersonIdType())) {
                linkman.setPersonIdType(null);
            }
            linkman.setPersonNum(this.getAttrValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_CARDNUM, "未配置【客户联系人证件号码】属性"));
            /*
             * 对接用户中心改造：需要新增changeType、startTime、endTime字段
             */
            if (CuccPosServiceUtils.isRouteUser(context.getSceneInstId(),context.getCustId())) {
                if(!KiteStringUtils.equals(contactAttrObj.getValue(), "T")) {
                    // 未选中的情况下，判断是否存在旧值，存在则说明此次操作非订购需删除，不存在则说明此次不调整代理商。
                    if(KiteStringUtils.isEmpty(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_NAME, ""))) {
                        return ;
                    }
                    linkman.setName(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_NAME, "未配置【客户联系人名称】属性"));
                    linkman.setPhone(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_TEL, "未配置【客户联系人电话】属性"));
                    linkman.setEmail(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_EMAIL, "未配置【客户联系人邮箱】属性"));
                    linkman.setAddress(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_ADDRESS, "未配置【客户联系人地址】属性"));
                    linkman.setFax(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_FAXNUM, "未配置【客户联系人传真号码】属性"));
                    linkman.setFixedPhone(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_FIXEDPHONE, "未配置【客户联系人固话号码】属性"));
                    linkman.setPostcode(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_POSTCODE, "未配置【客户联系人邮编】属性"));
                    linkman.setPersonIdType(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_CARDTYPE, "未配置【客户联系人证件类型】属性"));
                    linkman.setRemark(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_COMMENTS, "未配置【客户联系人备注】属性"));
                    if(Objects.nonNull(oldLinkman)) {
                        linkman.setStartTime(oldLinkman.getStartTime());
                        linkman.setEndTime(oldLinkman.getEndTime());
                    }
                    linkman.setPersonNum(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_CARDNUM, "未配置【客户联系人证件号码】属性"));
                    linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_D);
                }else {
                    // 非订购的情况下，需要传changeType、startTime、endTime字段
                    if (CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                        if(KiteStringUtils.isEmpty(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.CONTACT_INFO_NAME, ""))) {
                            linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                        }else {
                            if(Objects.nonNull(oldLinkman)) {
                                linkman.setStartTime(oldLinkman.getStartTime());
                                linkman.setEndTime(oldLinkman.getEndTime());
                            }
                            List<KiteAttr> changeKiteAttr = developerAttrs.stream().filter(attr -> !KiteStringUtils.equals(attr.getOriginValue(), attr.getValue())).collect(Collectors.toList());
                            if(KiteListUtils.isEmpty(changeKiteAttr)) {
                                linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);

                                if(Objects.nonNull(oldLinkman) && KiteStringUtils.equals(ChangeTypeUtils.CHANGE_TYPE_M, oldLinkman.getChangeType())) {
                                    if(KiteStringUtils.equals(serviceOfferId, "2826")) {
                                        String nodeCode = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "nodeCode");
                                        if(KiteStringUtils.equals(nodeCode, "OrderSigned")) {
                                            // 产品变更-签订，获取第一次提交时的changeType
                                            linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                                        }
                                    }
                                }
                            }else {
                                linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                            }
                        }
                    } else {
                        // 订购，资源核查等情况
                        if (KiteStringUtils.isEmpty(linkman.getChangeType())) {
                            linkman.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                        }
                    }
                }
            }
            context.getPosDto().setLinkman(linkman);
        }
	}

}
